package com.zl.easybuy.web;
import com.zl.easybuy.exc.EasyBuyExc;
import com.zl.easybuy.pojo.Order;
import com.zl.easybuy.pojo.UserAddress;
import com.zl.easybuy.service.OrderService;
import com.zl.easybuy.service.ShoppingCartService;
import com.zl.easybuy.service.UserAddressService;
import com.zl.easybuy.util.ShoppingCart;
import com.zl.easybuy.vo.ReaultVo;
import com.zl.easybuy.vo.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/Cart")
public class CartController {
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    UserAddressService userAddressService;
    @Autowired
    OrderService orderService;
    @RequestMapping("/add")
    @ResponseBody
    public ReaultVo addCart(Integer entityId, Integer quantity){
        try {
            boolean result=shoppingCartService.addShoppingCart(entityId,quantity);
            return result?ReaultVo.success(ResultCode.ADD_CART_SUCCESS):ReaultVo.success(ResultCode.ADD_CART_FAIL);
        }catch (EasyBuyExc e){
            return ReaultVo.fail(ResultCode.ADD_CART_FAIL);
        }
    }

    @PostMapping("/refreshCart")
    public String refreshCart(){
        return "forward:/common/pre/searchBar.jsp";
    }

    @GetMapping("/toSettlement")
    public String toSettlement(){
        return "forward:/pre/settlement/toSettlement.jsp";
    }

    @PostMapping("/settlement1")
    public String settlement1(){
        return "forward:/pre/settlement/settlement1.jsp";
    }

    @PostMapping("/settlement2")
    public String settlement2(Model model){
        //获取用户地址
        List<UserAddress> userAddress =userAddressService.findAddress();
        model.addAttribute("userAddressList",userAddress);
        return "forward:/pre/settlement/settlement2.jsp";
    }
    @PostMapping("/settlement3")
    public String settlement3(Integer addressId,String newAddress,String newRemark,Model model) throws EasyBuyExc{
        Order order=orderService.addOrder(addressId,newAddress,newRemark);
        model.addAttribute("currentOrder",order);
        return "forward:/pre/settlement/settlement3.jsp";
    }
    @PostMapping("/modCart")
    @ResponseBody
    public ReaultVo modCart(Integer entityId, Integer quantity){
       boolean result= shoppingCartService.modQuantity(entityId,quantity);
       return result?new ReaultVo(ResultCode.OP_SCUUESS):new ReaultVo(ResultCode.MODIFY_FAIL);
    }
}
